{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%load_ext autoreload\n",
    "%autoreload 2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import os\n",
    "import cv2\n",
    "from tqdm import tqdm\n",
    "import random\n",
    "import shutil\n",
    "\n",
    "from face_detector import FaceDetector"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "IMAGES_DIR = '/home/gpu2/hdd/dan/FDDB/originalPics/'\n",
    "ANNOTATIONS_PATH = '/home/gpu2/hdd/dan/FDDB/FDDB-folds/'\n",
    "RESULT_DIR = 'result/'\n",
    "MODEL_PATH = 'model.pb'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Collect annotated images"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "annotations = [s for s in os.listdir(ANNOTATIONS_PATH) if s.endswith('ellipseList.txt')]\n",
    "image_lists = [s for s in os.listdir(ANNOTATIONS_PATH) if not s.endswith('ellipseList.txt')]\n",
    "annotations = sorted(annotations)\n",
    "image_lists = sorted(image_lists)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "images_to_use = []\n",
    "for n in image_lists:\n",
    "    with open(os.path.join(ANNOTATIONS_PATH, n)) as f:\n",
    "        images_to_use.extend(f.readlines())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "images_to_use = [s.strip() for s in images_to_use]\n",
    "with open(os.path.join(RESULT_DIR, 'faceList.txt'), 'w') as f:\n",
    "    for p in images_to_use:\n",
    "        f.write(p + '\\n')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "ellipses = []\n",
    "for n in annotations:\n",
    "    with open(os.path.join(ANNOTATIONS_PATH, n)) as f:\n",
    "        ellipses.extend(f.readlines())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "i = 0\n",
    "with open(os.path.join(RESULT_DIR, 'ellipseList.txt'), 'w') as f:\n",
    "    for p in ellipses:\n",
    "        \n",
    "        # check image order\n",
    "        if 'big/img' in p:\n",
    "            assert images_to_use[i] in p\n",
    "            i += 1\n",
    "\n",
    "        f.write(p)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Predict using trained detector"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "face_detector = FaceDetector(MODEL_PATH, gpu_memory_fraction=0.25, visible_device_list='0')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "predictions = []\n",
    "for n in tqdm(images_to_use):\n",
    "    image_array = cv2.imread(os.path.join(IMAGES_DIR, n) + '.jpg')\n",
    "    image_array = cv2.cvtColor(image_array, cv2.COLOR_BGR2RGB)\n",
    "    # threshold is important to set low\n",
    "    boxes, scores = face_detector(image_array, score_threshold=0.05)\n",
    "    predictions.append((n, boxes, scores))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open(os.path.join(RESULT_DIR, 'detections.txt'), 'w') as f:\n",
    "    for n, boxes, scores in predictions:\n",
    "        f.write(n + '\\n')\n",
    "        f.write(str(len(boxes)) + '\\n')\n",
    "        for b, s in zip(boxes, scores):\n",
    "            ymin, xmin, ymax, xmax = b\n",
    "            h, w = int(ymax - ymin), int(xmax - xmin)\n",
    "            f.write('{0} {1} {2} {3} {4:.4f}\\n'.format(int(xmin), int(ymin), w, h, s))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Copy images"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for n in tqdm(images_to_use):\n",
    "    p = os.path.join(RESULT_DIR, 'images', n + '.jpg')\n",
    "    os.makedirs(os.path.dirname(p), exist_ok=True)\n",
    "    shutil.copy(os.path.join(IMAGES_DIR, n) + '.jpg', p)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
